package j2EE.servlet;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created with Intel IDEA.
 * 装饰过滤器
 * @Auther: gjt
 * @Date: 2024/9/1 13:25
 */
public class RequestInfoFilter implements Filter {
    // 描述过滤器配置
    FilterConfig filterConfig = null;

    // 构造器中无操作
    public RequestInfoFilter(){}

    // 只是保存FilterConfig
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletContext sc = filterConfig.getServletContext();

        // 预处理请求(继承)
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        sc.log("Request Attributes");
        sc.log("Method: " + httpServletRequest.getMethod());
        sc.log("QueryString" + httpServletRequest.getQueryString());
        sc.log("RequestUrl" + httpServletRequest.getRequestURL());
        sc.log("RequestUri" + httpServletRequest.getRequestURI());
        sc.log("PathInfo" + httpServletRequest.getPathInfo());
        sc.log("Parameters");

        // 枚举出所有的请求参数
       for(Enumeration e = httpServletRequest.getParameterNames(); e.hasMoreElements();){
           String name = (String) e.nextElement();
           String[] parameterValues = httpServletRequest.getParameterValues(name);
           StringBuilder values = new StringBuilder();
           values.append(name + "=");

           // 每个参数可能有多个值
           for (int i = 0; i < parameterValues.length; i++) {
               values.append(parameterValues[i] + ",");
           }
           // 去掉最后边的逗号
           sc.log(values.substring(0, values.length() - 1));
       }

        /**
         *  在链中调用一下过滤器流
         */
        filterChain.doFilter(servletRequest, servletResponse);
    }


    // 在过滤器无效时调用
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
